import React from 'react';
import { render, screen } from '@testing-library/react';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import Home from './Home';

const middlewares = [thunk];
const mockStore = configureStore(middlewares);

describe('Home Component', () => {
    let store: ReturnType<typeof mockStore>;

    beforeEach(() => {
        store = mockStore({
            categories: {
                data: [
                    { key: '1', title: 'Category 1' },
                    { key: '2', title: 'Category 2' }
                ]
            }
        });

        store.dispatch = jest.fn();
    });

    it('should dispatch fetchCategories on mount', () => {
        render(
            <Provider store={store}>
                <BrowserRouter>
                    <Home />
                </BrowserRouter>
            </Provider>
        );

        expect(store.dispatch).toHaveBeenCalled();
    });

    it('should render categories if available', () => {
        render(
            <Provider store={store}>
                <BrowserRouter>
                    <Home />
                </BrowserRouter>
            </Provider>
        );

        expect(screen.getByText('Category 1')).toBeInTheDocument();
        expect(screen.getByText('Category 2')).toBeInTheDocument();
    });

    it('should render "No categories" if no categories are available', () => {
        store = mockStore({
            categories: {
                data: []
            }
        });

        render(
            <Provider store={store}>
                <BrowserRouter>
                    <Home />
                </BrowserRouter>
            </Provider>
        );

        expect(screen.getByText('No categories')).toBeInTheDocument();
    });

    it('should render correct links for categories', () => {
        render(
            <Provider store={store}>
                <BrowserRouter>
                    <Home />
                </BrowserRouter>
            </Provider>
        );

        const links = screen.getAllByRole('link');
        expect(links[0]).toHaveAttribute('href', '/categories/1');
        expect(links[1]).toHaveAttribute('href', '/categories/2');
    });
});
